package com.goldcn.picture.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.goldcn.common.CommonTools;
import com.goldcn.common.DataUtils;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.enumeration.ErrorCodeEnum;
import com.goldcn.enumeration.OperateTypeEnum;
import com.goldcn.goods.dto.PageInfo;
import com.goldcn.goods.model.GoodsSku;
import com.goldcn.goods.service.GoodsService;
import com.goldcn.goods.vo.GoodsDetailsVo;
import com.goldcn.goods.vo.GoodsInfoVo;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.picture.dao.*;
import com.goldcn.picture.dto.QueryPicInfoDto;
import com.goldcn.picture.dto.QueryResultPicInfoDto;
import com.goldcn.picture.dto.QueryResultTagDto;
import com.goldcn.picture.model.*;
import com.goldcn.picture.vo.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class PictureService {

    @Autowired
    PicInfoMapper picInfoMapper;

    @Autowired
    PicSkuMapper picSkuMapper;

    @Autowired
    PicEnshrineMapper picEnshrineMapper;

    @Autowired
    PicRecordMapper picRecordMapper;

    @Autowired
    PicLabelDetailMapper picLabelDetailMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    GoodsService goodsService;

    @Autowired
    PicLabelMapper picLabelMapper;

    @Autowired
    PicSpecialMapper picSpecialMapper;

    @Autowired
    PicSpecialDetailMapper picSpecialDetailMapper;

    @Autowired
    PicAttrStoneMapper picAttrStoneMapper;

    @Autowired
    PicInfoItemMapper picInfoItemMapper;

    @Autowired
    PicEntityAttrMapper picEntityAttrMapper;

    @Autowired
    PicImagesMapper picImagesMapper;

    @Autowired
    PicFactoryMapper picFactoryMapper;

    @Autowired
    PicBrandMapper picBrandMapper;

    @Autowired
    PicSysTagsItemMapper picSysTagsItemMapper;

    @Autowired
    PicTemplateMapper templateMapper;


    @Autowired
    PicRelationMapper picRelationMapper;



    /**
     * 添加图片信息
     * @param picInfoDetailVo
     * @return
     */
    public Integer addPicInfo(PicInfoDetailVo picInfoDetailVo){

        //try {
            PicInfo picInfo = new PicInfo();
            PicAttrStone picAttrStone = new PicAttrStone();
            Integer result = 0;
            //设置默认供应商
            if (picInfoDetailVo.getPicInfo().getSupplierid()==null){
                picInfoDetailVo.getPicInfo().setSupplierid(998480474374410240L);
            }
            if (picInfoDetailVo.getPicInfo().getSuppliername()==null){
                picInfoDetailVo.getPicInfo().setSuppliername("蓝帝珠宝有限公司");
            }
            BeanUtils.copyProperties(picInfoDetailVo.getPicInfo(), picInfo);
            BeanUtils.copyProperties(picInfoDetailVo.getPicAttrStone(), picAttrStone);

            switch (picInfoDetailVo.getOperateType()) {
                case insert:
                    picInfo.setPictureid(IdGen.get().nextId());
                    picInfo.setAddtime(CommonUtils.getCurTimestamp());
                    picInfo.setAuditstatus(0);

                    Map<String,Object> map=SystemContext.getToken();
                    picInfo.setPictureauthor(map.get("userName")!=null?map.get("userName").toString():"");
                    picInfo.setUserid(map.get("userId")!=null?Long.parseLong(map.get("userId").toString()):picInfoDetailVo.getPicInfo().getUserid());
                    if (picInfoDetailVo.getPicInfo().getPicturetype()==1){
                        picInfo.setPicturesource("手绘");
                    }else{
                        picInfo.setPicturesource("其它");
                    }
                    picInfoDetailVo.getPicInfo().setPictureid(picInfo.getPictureid());
                    break;
                case update:
                    picInfo.setUpdatetime(CommonUtils.getCurTimestamp());
                    picInfo.setUpdateuser(picInfoDetailVo.getPicInfo().getUserid());
                    break;
            }



            //默认以第一张为主图
            if (picInfoDetailVo.getPicImgs()!=null && picInfoDetailVo.getPicImgs().size() > 0) {
                picInfo.setPictureurl(picInfoDetailVo.getPicImgs().get(0).getUrl());
            }

            picAttrStone.setPictureid(picInfo.getPictureid());
            //插入图片主表信息
            operatorPicInfo(picInfo, picInfoDetailVo.getOperateType());
            //添加图片表
            operatorPicImages(picInfo, picInfoDetailVo.getPicImgs(), picInfoDetailVo.getOperateType());

            //插入详细信息
            operatorPicInfoAttrStone(picAttrStone, picInfo.getPictureid());

            //插入图片SKU信息
            batchInsertPicSku(picInfo.getPictureid(), picInfoDetailVo.getPicSkuList(), picInfoDetailVo.getOperateType());

            //插入图片标签
            batchInsertPicLabels(picInfo.getPictureid(), picInfoDetailVo.getPicLabels());



            //类型3D图片时，多颗宝石信息

            if (picInfoDetailVo.getItemList()!=null && picInfoDetailVo.getItemList().size() > 0) {
                picInfoItemMapper.deleteByPictureId(picInfo.getPictureid());
                for (PicInfoItem infoItem : picInfoDetailVo.getItemList()) {
                    infoItem.setItemid(IdGen.get().nextId());
                    infoItem.setPictureid(picInfo.getPictureid());
                    picInfoItemMapper.insertSelective(infoItem);
                }
            }


            //如果是商品实物图，则把数据同步到商品库里
            if (picInfo.getPicturetype() == 5) {
                sysGoodsData(picInfoDetailVo);
            }


            if (picInfo.getPicturetype() == 7) {
                //品牌信息
                PicBrand brand=picInfoDetailVo.getPicBrand();
                if (brand!=null){
                    //先删除品牌信息
                    picBrandMapper.deleteByPictureid(picInfo.getPictureid());
                    brand.setBrandid(IdGen.get().nextId());
                    brand.setPictureid(picInfo.getPictureid());
                    picBrandMapper.insertSelective(brand);
/*                    if (brand.getBrandid()!=null){
                        picBrandMapper.updateByPrimaryKeySelective(brand);
                    }else{
                        brand.setBrandid(IdGen.get().nextId());
                        brand.setPictureid(picInfo.getPictureid());
                        picBrandMapper.insertSelective(brand);
                    }*/
                }
            }
            return result;
/*        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            log.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.addPicinfoFailure);
        }*/
    }


    /**
     * 更新图片
     * @param list
     * @param state
     */
    public void operatorPicImages(PicInfo picInfo,List<PicImagesVo> list, OperateTypeEnum state){
        if (list!=null) {
            if (list.size() > 0) {
                if (OperateTypeEnum.update.equals(state)) {
                    picImagesMapper.deleteByPicId(picInfo.getPictureid());
                }
                int index = 0;
                for (PicImagesVo vo : list) {
                    PicImages picImages = new PicImages();
                    if (vo.getUrl() != null && !vo.getUrl().equals("")) {
                        picImages.setImgid(IdGen.get().nextId());
                        picImages.setPictureid(picInfo.getPictureid());
                        picImages.setUrl(vo.getUrl());
                        picImages.setImgdes(vo.getImgdes());
                        picImages.setSeq(index);
                        picImagesMapper.insertSelective(picImages);
                        index++;
                    }
                }
            }
        }
    }


    /**
     * 更新图片信息库
     * @param picInfo
     * @param state
     */
    public void operatorPicInfo(PicInfo picInfo, OperateTypeEnum state){
        Integer result=0;
        if (OperateTypeEnum.update.equals(state)){
            result=picInfoMapper.updateByPrimaryKeySelective(picInfo);
        }else {
            //默认供应商
            //picInfo.setSupplierid(998480474374410240L);
            //picInfo.setSuppliername("蓝帝珠宝有限公司");
            result=picInfoMapper.insertSelective(picInfo);
        }

    }

    /**
     * 图片实物同步数据到商品库
     */
    public void sysGoodsData(PicInfoDetailVo picInfoDetailVo){
        GoodsDetailsVo goodsDetailsVo =new GoodsDetailsVo();

        //商品基本信息
        GoodsInfoVo goodsInfoVo=new GoodsInfoVo();
        PicInfo picInfo=picInfoMapper.selectByPrimaryKey(picInfoDetailVo.getPicInfo().getPictureid());
        if(picInfoDetailVo.getOperateType().getValue()==1){
            //goodsInfoVo.setGoodsID(picInfo.getGoodsid());
            //删除之前同步的商品数据
            goodsService.delGoodsByGoodsID(picInfo.getGoodsid());
        }
        goodsInfoVo.setAddTime(CommonUtils.getCurTimestamp());
        goodsInfoVo.setName(picInfoDetailVo.getPicInfo().getPicturename());
        goodsInfoVo.setTitle(picInfoDetailVo.getPicInfo().getPicturedescribe());
        goodsInfoVo.setClassifyID(picInfoDetailVo.getPicInfo().getClassifyid());
        goodsInfoVo.setSubClassifyID(picInfoDetailVo.getPicInfo().getSubclassifyid());
        goodsInfoVo.setClassifyName(picInfoDetailVo.getPicInfo().getClassifyname());
        goodsInfoVo.setSubClassifyName(picInfoDetailVo.getPicInfo().getSubclassifyname());
        goodsInfoVo.setOpreateUser(picInfoDetailVo.getPicInfo().getUserid());
        goodsInfoVo.setCompayID(SystemContext.getCompanyID());
        goodsInfoVo.setSupplierID(picInfoDetailVo.getPicInfo().getSupplierid());
        goodsInfoVo.setSupplierName(picInfoDetailVo.getPicInfo().getSuppliername());
        goodsInfoVo.setAttr(picInfoDetailVo.getPicInfo().getAttr());
        //goodsInfoVo.setClassifyID(picInfoDetailVo.getPicInfo().getClassifyid());
        goodsDetailsVo.setGoodsInfoVo(goodsInfoVo);

        //商品图片
        List<String> imageUrlList=new ArrayList<>();
        if(picInfoDetailVo.getPicImgs()!=null && picInfoDetailVo.getPicImgs().size()>0){
            for (PicImagesVo vo:picInfoDetailVo.getPicImgs()){
                if (vo.getUrl()!=null && !vo.getUrl().equals("")){
                    imageUrlList.add(vo.getUrl());
                }
            }
        }
        goodsDetailsVo.setImageUrlList(imageUrlList);

        //商品SKU
        List<GoodsSku> goodsSkuList=new ArrayList<>();
        if(picInfoDetailVo.getPicSkuList()!=null && picInfoDetailVo.getPicSkuList().size()>0){
            for (PicSku sku:picInfoDetailVo.getPicSkuList()){
                GoodsSku goodsSku=new GoodsSku();
                goodsSku.setSkuID(IdGen.get().nextId());
                goodsSku.setAttrJson(sku.getArrtjson());
                goodsSku.setPrice(sku.getRetailprice());
                goodsSkuList.add(goodsSku);
            }
        }
        goodsDetailsVo.setGoodsSkuList(goodsSkuList);
        goodsDetailsVo.setOperateType(OperateTypeEnum.insert);

        Long goodId=goodsService.operateGoods(goodsDetailsVo);

        //更新图片库关联商品ID
        if(picInfoDetailVo.getOperateType().getValue()==0){
            picInfo.setGoodsid(goodId);
            picInfoMapper.updateByPrimaryKey(picInfo);
        }
    }


    /**
     * 插入详细信息库
     */
    public void operatorPicInfoAttrStone( PicAttrStone picAttrStone,Long picid){
        //先删除记录
        picAttrStoneMapper.deleteByPictureId(picid);

        picAttrStone.setStoneid(IdGen.get().nextId());
        //保存详细信息
        picAttrStoneMapper.insertSelective(picAttrStone);
    }

    /**
     * 插入图片SKU
     * @param picSkus
     * @param state
     */
    public void batchInsertPicSku(Long picID,List<PicSku> picSkus, OperateTypeEnum state){
        Integer result=0;
        if (OperateTypeEnum.update.equals(state)){
            //先删除SKU信息
            picSkuMapper.deleteByPictureId(picID);
        }
        int index=0;
        for (PicSku picSku:picSkus){
            picSku.setPictureid(picID);
            picSku.setSkuid(IdGen.get().nextId());
            picSku.setSeq(index);
            picSkuMapper.insertSelective(picSku);
            index++;
        }
        //picSkuMapper.insertBatch(picSkus);
        savePicAttrStone(picSkus);
    }

    /**
     * 添加宝石属性SKU
     * @param picSkuList
     * @return
     */
    public int savePicAttrStone(List<PicSku> picSkuList) {
        List<PicEntityAttr> stones=new ArrayList<>();

        //List<GoodsAttrStone> stones = new ArrayList<>();
        for (PicSku sku : picSkuList) {
            PicEntityAttr stone = new PicEntityAttr();
            stone.setPictureid(sku.getPictureid());
            stone.setEntityid(IdGen.get().nextId());
            stone.setSkuid(sku.getSkuid());
            System.out.println(sku.getArrtjson());
            JSONObject obj = JSONObject.fromObject(sku.getArrtjson());
/*            String goodsAttr_temp = sku.getGoodsAttr().replace("null,", "");//中间或最前面的null
            //logger.info("goodsAttr_temp===" + goodsAttr_temp);
            goodsAttr_temp = goodsAttr_temp.replace("null", "");//最后面的null
            List<JSONObject> goodsJsonList = JsonUtil.toList(goodsAttr_temp);
            //logger.info("objAku===" + obj);
            for (JSONObject goodsAttr : goodsJsonList) {
                if (!obj.containsKey(goodsAttr.get("clazzattrcode"))) {
                    obj.put(goodsAttr.get("clazzattrcode"), goodsAttr.get("clazzattrval"));
                }

            }*/
            //logger.info("obj===" + obj);
            stone.setHxcuttype(DataUtils.getStr(obj, "hxCutType", null));
            stone.setHxcolor(DataUtils.getStr(obj, "hxColor", null));
            stone.setHxshape(DataUtils.getStr(obj, "hxShape", null));
            stone.setHxneatness(DataUtils.getStr(obj, "hxNeatness", null));
            stone.setHxlucency(DataUtils.getStr(obj, "hxLucency", null));
            stone.setHxcutgrade(DataUtils.getStr(obj, "hxCutGrade", null));
            stone.setHxfiregrade(DataUtils.getStr(obj, "hxFireGrade", null));
            // stone.setHxSize(obj.containsKey("hxSize")?new BigDecimal(obj.get("hxSize").toString()):null);//类型为中英文字符

            //stone.setWeight(obj.containsKey("weight") ? !obj.get("weight").equals("")?new BigDecimal(obj.get("weight").toString().trim()):null : null);
            stone.setMsclarity(DataUtils.getStr(obj, "msClarity", null));
            stone.setMscolor(DataUtils.getStr(obj, "msColor", null));
            stone.setMscut(DataUtils.getStr(obj, "msCut", null));
            stone.setMsweight(DataUtils.getStr(obj, "msWeight", null));
            stone.setGgcertnum(DataUtils.getStr(obj, "GGcertNum", null));
            stone.setHxcolorgrade(DataUtils.getStr(obj, "hxColorGrade", null));
            stone.setHxstore(DataUtils.getStr(obj, "hxStore", null));
            stone.setHxgradeno(DataUtils.getStr(obj, "hxGradeNO", null));
            stone.setHxhandlemethod(DataUtils.getStr(obj, "hxHandleMethod", null));
            stone.setHxpolish(DataUtils.getStr(obj, "hxPolish", null));
            stone.setHxsym(DataUtils.getStr(obj, "hxSym", null));
            stone.setHxlight(DataUtils.getStr(obj, "hxLight", null));
            stone.setGgcertorg(DataUtils.getStr(obj, "GGcertOrg", null));
            stone.setHxbrand(DataUtils.getStr(obj, "hxBrand", null));
            stone.setHxcraft(DataUtils.getStr(obj, "hxCraft", null));
            //stone.setHxhandsize(obj.containsKey("hxHandSize") ? !obj.get("hxHandSize").equals("")?new BigDecimal(obj.get("hxHandSize").toString().trim()):null : null);
            stone.setHxcertorg(DataUtils.getStr(obj, "hxCertOrg", null));
            stone.setHxinlay(DataUtils.getStr(obj, "hxInlay", null));

            stone.setSscertnum(DataUtils.getStr(obj,"ssCertNum"));
            stone.setSscertorg(DataUtils.getStr(obj,"ssCertorg"));
            stone.setSsclarity(DataUtils.getStr(obj,"ssClarity"));
            stone.setSellrate(DataUtils.getStr(obj,"sellRate"));
            stone.setSelltype(DataUtils.getStr(obj,"sellType"));
            stone.setSsname(DataUtils.getStr(obj,"ssName"));
            stone.setSscolor(DataUtils.getStr(obj,"ssColor"));
            stone.setSscount(DataUtils.getStr(obj,"ssCount"));
            stone.setSsheight(DataUtils.getStr(obj,"ssHeight"));
            stone.setSsweight(DataUtils.getStr(obj,"ssWeigth"));
            stone.setSsnumber(DataUtils.getStr(obj,"ssNumber"));
            stone.setSssize(DataUtils.getStr(obj,"ssSize"));


            //stone.setSssum();
            picEntityAttrMapper.insertSelective(stone);

        }
        return 0;

    }

    /**
     * 批量更新图片标签
     */
    public void batchInsertPicLabels(Long picID,List<Long> labelList){
        try{
            if (labelList==null || labelList.size()<=0){
                return;
            }
            //先删除图片标签
            picLabelDetailMapper.deleteByPictureId(picID);

            int index=0;
            for (Long label:labelList){
                PicLabelDetail detail=new PicLabelDetail();
                detail.setAddtime(CommonUtils.getCurTimestamp());
                detail.setLabeldetailid(IdGen.get().nextId());
                detail.setPictureid(picID);
                detail.setLabelid(label);
                detail.setSeq(index);
                picLabelDetailMapper.insertSelective(detail);
                index++;
            }

        }catch (Exception e){
            log.info(e.getMessage());
        }
    }



    /**
     * 通过ID删除指定的图片
     * @param picID
     * @return
     */
    public Integer deleteByPrimaryKey(Long picID){
        //判断标签是否使用
/*        if(picLabelMapper.labelUseCount(labelID)>0){
            throw CommonTools.createException(ErrorCodeEnum.lableIsUsed);
        }*/
        Integer result = picInfoMapper.deleteByPrimaryKey(picID);
        if(result!=1){
            //抛出异常
            throw CommonTools.createException(ErrorCodeEnum.deleteSpecialFailure);
        }
        picSkuMapper.deleteByPicid(picID);
        picAttrStoneMapper.deleteByPictureId(picID);
        //删除图片标签
        picLabelDetailMapper.deleteByPictureId(picID);
        //删除图片专题
        picSpecialDetailMapper.deleteByPictureId(picID);

        PicInfo picInfo=picInfoMapper.selectByPrimaryKey(picID);
        //删除商品库同步的数据
        if (picInfo.getGoodsid()!=null){
            goodsService.delGoodsByGoodsID(picInfo.getGoodsid());
        }

        return result;
    }

    /**
     * 根据ID查询图片
     * @param picID
     * @return
     */
    public QueryResultPicInfoDto selectByPrimaryKey(Long picID){
        QueryResultPicInfoDto queryResultPicInfoDto=new QueryResultPicInfoDto();
        PicInfo info=picInfoMapper.selectByPrimaryKey(picID);


        BeanUtils.copyProperties(info, queryResultPicInfoDto);

        //图片标签
        queryResultPicInfoDto.setLabelList(picLabelMapper.getPicLableList(picID));
        //专题信息
        queryResultPicInfoDto.setSpecialList(picSpecialMapper.selectListByPictureId(picID));
        //图片SKU
        queryResultPicInfoDto.setSkuList(picSkuMapper.selectListByPictureId(picID));
        //图片属性
        queryResultPicInfoDto.setPicAttr(picAttrStoneMapper.selectListByPictureId(picID));

        //三D图属性
        queryResultPicInfoDto.setItemList(picInfoItemMapper.selectListBypictureId(picID));

        //品牌信息
        queryResultPicInfoDto.setPicBrand(picBrandMapper.selectByPictureid(picID));
        //工厂信息
        queryResultPicInfoDto.setPicFactory(picFactoryMapper.selectByPictureId(picID));
        //多图片
        queryResultPicInfoDto.setImagesList(picImagesMapper.selectByPictureid(picID));

        //系统标签
        List<QueryResultTagDto>  tagList=new ArrayList<>();
        List<Map> list=picSysTagsItemMapper.selectListByPictureid(picID);
        if (list.size()>0){
            for (Map map:list){
                QueryResultTagDto dto=new QueryResultTagDto();
                dto.setTagid(Long.parseLong(map.get("tagID").toString()));
                dto.setTaggroup(map.get("tagGroup").toString());
                dto.setTagsItemList(picSysTagsItemMapper.selectListByPicTag(dto.getTagid(),picID));
                tagList.add(dto);
            }
        }
        //系统标签
        queryResultPicInfoDto.setTagsItems(tagList);

        //统计查看数量
        Object ojbect=redisTemplate.opsForValue().get("pic_"+picID);
        if (ojbect!=null){
            info.setVisitamount(Long.parseLong(ojbect.toString()));
            picInfoMapper.updateByPrimaryKeySelective(info);
        }
        return queryResultPicInfoDto;
    }

    /**
     * 根据ID查询图片
     * @param picID
     * @return
     */
    public PicInfo selectByPicture(Long picID){
        QueryResultPicInfoDto queryResultPicInfoDto=new QueryResultPicInfoDto();
        PicInfo info=picInfoMapper.selectByPrimaryKey(picID);
        return info;
    }


    /**
     * 用户收藏
     * @param picEnshrineVo
     * @return
     */
    public Object userPicEnshrine(PicEnshrineVo picEnshrineVo){

        if(picEnshrineMapper.selectByUserPic(picEnshrineVo.getUserid(),picEnshrineVo.getPictureid())>0){
            throw CommonTools.createException(ErrorCodeEnum.addEnshrineFailure);
        }
        PicEnshrine picEnshrine=new PicEnshrine();
        picEnshrine.setAddtime(CommonUtils.getCurTimestamp());
        picEnshrine.setEnshrineid(IdGen.get().nextId());
        picEnshrine.setPictureid(picEnshrineVo.getPictureid());
        picEnshrine.setIsdelete(0L);
        picEnshrine.setUserid(picEnshrineVo.getUserid());
        picEnshrine.setUsername(picEnshrineVo.getUsername());

        int result= picEnshrineMapper.insertSelective(picEnshrine);

        //保存收藏记录
        PicRecord record =new PicRecord();
        record.setAddtime(CommonUtils.getCurTimestamp());
        record.setRecordid(IdGen.get().nextId());
        record.setPictureid(picEnshrineVo.getPictureid());
        record.setUserid(picEnshrineVo.getUserid());
        record.setUsername(picEnshrineVo.getUsername());
        record.setRecordtype(0);
        record.setChannelid(picEnshrine.getEnshrineid());
        picRecordMapper.insertSelective(record);

        return result;

    }



    /**
     * 用户取消收藏
     * @param
     * @return
     */
    public Object userCancelEnshrine(PicEnshrineVo picEnshrineVo){

        return picEnshrineMapper.deleteByUserEnshrine(picEnshrineVo.getUserid(),picEnshrineVo.getPictureid());

    }


    /**
     * 图片列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Object queryListPicInfo(Integer pageNum, Integer pageSize){
        //String orderBy = "addTime";
        //String orderType = "desc";
        PageHelper.startPage(pageNum, pageSize);//分页初始化
        Page page = (Page) picInfoMapper.queryListPicInfo();

        return new PageInfo(page, page.getPages(), page.getTotal());
    }


    /**
     * 图片列表(出入库使用)
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Object queryListPicInfos(Integer pageNum, Integer pageSize){
        //String orderBy = "addTime";
        //String orderType = "desc";
        PageHelper.startPage(pageNum, pageSize);//分页初始化
        Page page = (Page) picInfoMapper.queryListPicInfos();

        return new PageInfo(page, page.getPages(), page.getTotal());
    }


    /**
     * 条件查询图片
     * @param queryPicInfoDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Object queryListPicInfo(QueryPicInfoDto queryPicInfoDto,Integer pageNum, Integer pageSize){
        String orderBy = "addTime";
        String orderType = "desc";
        String orderStr = "info." + orderBy + " " + orderType;
        PageHelper.startPage(pageNum, pageSize,orderStr);//分页初始化

        List<QueryResultPicInfoDto> list=picInfoMapper.queryListPicInfoV2(queryPicInfoDto);

        //系统标签
  /*      if (list.size()>0){
            for (QueryResultPicInfoDto dto:list){
                List<QueryResultTagDto>  tagList=new ArrayList<>();
                List<Map> listTag=picSysTagsItemMapper.selectListByPictureid(dto.getPictureid());
                if (listTag.size()>0){
                    for (Map map:listTag){
                        QueryResultTagDto tagDto=new QueryResultTagDto();
                        tagDto.setTagid(Long.parseLong(map.get("tagID").toString()));
                        tagDto.setTaggroup(map.get("tagGroup").toString());
                        List<PicSysTagsItem> itemList=picSysTagsItemMapper.selectListByPicTag(tagDto.getTagid(),dto.getPictureid());
                        if (itemList.size()>3){
                            tagDto.setTagsItemList(itemList.subList(0,2));
                        }else{
                            tagDto.setTagsItemList(itemList);
                        }
                        tagList.add(tagDto);
                    }
                }
                dto.setTagsItems(tagList);
            }
        }
*/
        if (list.size()>0){
            for (QueryResultPicInfoDto dto:list){
                List<QueryResultTagDto>  tagList=new ArrayList<>();
                List<PicSysTagsItem> itemList=picSysTagsItemMapper.selectListByPicid(dto.getPictureid());
                if (itemList.size()>3){
                    dto.setSysTagsItems(itemList.subList(0,3));
                }else{
                    dto.setSysTagsItems(itemList);
                }
            }
        }

        Page page = (Page) list;

        return new PageInfo(page, page.getPages(), page.getTotal());
    }

    /**
     * 查询用户收藏
     * @param userID
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Object selectUserPicEnshrine(Long userID,Integer pageNum, Integer pageSize){

        PageHelper.startPage(pageNum, pageSize);//分页初始化
        Page page = (Page) picEnshrineMapper.selectUserPicEnshrine(userID);

        return new PageInfo(page, page.getPages(), page.getTotal());

    }

    /**
     * 删除收藏
     * @param enshrineid
     * @return
     */
    public int delUserPicEnshrine(Long enshrineid){
        return picEnshrineMapper.deleteByPrimaryKey(enshrineid);
    }



    /**
     * 查询用户图片
     * @param
     * @return
     */
    public Object queryListPicInfoByUser(PicInfoByUserVo picInfoByUserVo,Integer pageNum, Integer pageSize){

        PageHelper.startPage(pageNum, pageSize);//分页初始化
        Page page = (Page) picInfoMapper.queryListPicInfoByUser(picInfoByUserVo);
        return new PageInfo(page, page.getPages(), page.getTotal());
    }

    /**
     * 审核图片
     * @param vo
     * @return
     */
    public Object auditPicInfo(PicAuditVo vo){
        PicInfo picInfo=picInfoMapper.selectByPrimaryKey(vo.getOperatorid());
        if (picInfo.getAuditstatus()>0){
            throw CommonTools.createException(ErrorCodeEnum.auditStorageFailure);
        }
        picInfo.setAuditstatus(vo.getStatus());
        picInfo.setAuditdes(vo.getAuditdes());
        int result=picInfoMapper.updateByPrimaryKey(picInfo);
        return result;
    }

    /**
     * 检查图片编号的唯一性
     * @param pictureno
     * @return
     */
    public Object checkPictureNo(String pictureno){
        return picInfoMapper.checkPictureNo(pictureno);
    }

    /**
     * 系统标签查询图片
     * @param picTagVo
     * @return
     */
    public Object queryListPicInfoByTag(PicTagVo picTagVo){
        return  picInfoMapper.queryListPicInfoByTag(picTagVo);
    }


    /**
     * 图片上架下架
     * @param picPutVo
     * @return
     */
    public Object operatorPicStatus(PicPutVo picPutVo){
        PicInfo picInfo=picInfoMapper.selectByPrimaryKey(picPutVo.getPictureid());
        int result=0;
        if (picInfo.getPicturetype()!=5){
            throw CommonTools.createException(ErrorCodeEnum.operatorPicinfoFailure);
        }else{
            picInfo.setPicturestatus(picPutVo.getStatus());
            picInfo.setSellcase(picPutVo.getSellcase());
            result=picInfoMapper.updateByPrimaryKeySelective(picInfo);
        }
        return result;
    }

    /**
     * 图片下载
     * @param pictureid
     * @return
     */
    public Object downfile(Long pictureid){
        int result=0;
        PicInfo picInfo=picInfoMapper.selectByPrimaryKey(pictureid);
        picInfo.setDownloadamount(picInfo.getDownloadamount()+1);
        result=picInfoMapper.updateByPrimaryKeySelective(picInfo);
        return result;
    }


    /**
     * 检查用户是否收藏图片
     * @param pictureid
     * @param userid
     * @return
     */
    public Object checkUserEnshrine(Long pictureid,Long userid){
        Integer result=picEnshrineMapper.selectByUserPic(userid,pictureid);
        return result;
    }


    /**
     * 获取模板
     * @param classifyid
     * @param subclassifyid
     * @return
     */
    public Object selectByTemplate(String classifyid,String subclassifyid){
        return templateMapper.selectByTemplate(classifyid,subclassifyid);
    }

    /**
     * 图片关联关系
     * @param picRelationVo
     * @return
     */
    public Object pictureRelation(PicRelationVo picRelationVo){
        int result=0;
        if (picRelationVo.getRelationid()!=null && picRelationVo.getRelationid().size()>0){
            for (Long rid:picRelationVo.getRelationid()){
              PicRelation picRelation=new PicRelation();
              picRelation.setPictureid(picRelationVo.getPictureid());
              picRelation.setRid(IdGen.get().nextId());
              picRelation.setRelationid(rid);
              picRelation.setRelationinfo(picRelationVo.getRelationinfo());
              result=picRelationMapper.insertSelective(picRelation);

            }
        }
        return result;
    }


}
